<template>
  <a-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="mainId">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button v-if="!editable" type="primary" icon="edit" @click="handleEditBatch" v-show="!isChecked">编辑</a-button>
      <a-button
        v-show="editable"
        type="primary"
        icon="save"
        :style="{ backgroundColor: saveColor, borderColor: saveColor }"
        @click="handleSaveBatch"
        >保存
      </a-button>
      <a-button
        v-show="editable"
        type="primary"
        icon="rollback"
        :style="{ backgroundColor: cancelColor, borderColor: cancelColor }"
        @click="handleCancel"
        >取消
      </a-button>
      <a-button
        v-show="editable && selectedRowKeys.length !== 0"
        type="primary"
        icon="delete"
        :style="{ backgroundColor: deleteColor, borderColor: deleteColor }"
        @click="handleDeleteVirtual"
        >删除
      </a-button>
      <a-button @click="printAll" type="primary" icon="printer" v-show="!isChecked">打印</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        :rowKey="uniqueField"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="materialCode" slot-scope="text, record">
          <div>
            <HfMaterialSearchSelectTag
              v-if="record.add"
              :data-url="url.materialList"
              v-model="record.materialCode"
              @change="onMaterialChange(arguments, record)"
            ></HfMaterialSearchSelectTag>
            <template v-else slot-scope="text, record">
              {{ record.materialCode }}
            </template>
          </div>
        </template>

        <template slot="goodCounts" slot-scope="text, record">
          <a-input-number v-model:value="record.goodCounts" v-if="editable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="defectiveCounts" slot-scope="text, record">
          <a-input-number v-model:value="record.defectiveCounts" v-if="editable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="scrapCounts" slot-scope="text, record">
          <a-input-number v-model:value="record.scrapCounts" v-if="editable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="editable-row-operations" v-show="record.status !== 1">
            <a :disabled="!record.editable" @click="handleDelete(record.materialCode)">删除</a>
          </div>
        </template>
      </a-table>
    </div>
    <HfReworkDetailModal
      ref="modalForm"
      @ok="modalFormOk"
      :mainId="mainId"
      :materialCodes="materialCodes"
    ></HfReworkDetailModal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import store from '@/store'
import { deleteAction, getAction, postAction, putAction } from '@api/manage'
import { ajaxGetDictItems } from '@api/api'
import { objectMerge } from '@/utils/util'
import HfReworkDetailModal from '@views/production/modules/HfReworkDetailModal.vue'
import { Modal } from 'ant-design-vue'

export default {
  name: 'HfReworkDetailList',
  mixins: [JeecgListMixin],
  components: { HfReworkDetailModal, HfMaterialSearchSelectTag },
  props: ['mainId'],
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    return {
      description: '返工管理管理页面',
      disableMixinCreated: true,
      isChecked: false,
      editable: false,
      materialCodes: [],
      compareFields: ['materialCode', 'goodCounts', 'defectiveCounts', 'scrapCounts'],
      uniqueField: 'materialCode',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '返工数量',
          align: 'center',
          dataIndex: 'reworkCounts',
          customRender: (text, record) => {
            return record['goodCounts'] + record['defectiveCounts'] + record['scrapCounts']
          }
        },
        {
          title: '良品数',
          align: 'center',
          dataIndex: 'goodCounts',
          scopedSlots: { customRender: 'goodCounts' }
        },
        {
          title: '不良品数',
          align: 'center',
          dataIndex: 'defectiveCounts',
          scopedSlots: { customRender: 'defectiveCounts' }
        },
        {
          title: '报废品数',
          align: 'center',
          dataIndex: 'scrapCounts',
          scopedSlots: { customRender: 'scrapCounts' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/production/hfRework/listHfReworkDetailByMainId',
        delete: '/production/hfRework/deleteHfReworkDetail',
        deleteBatch: '/production/hfRework/deleteBatchHfReworkDetail',
        exportXlsUrl: '/production/hfRework/exportHfReworkDetail',
        importUrl: '/production/hfRework/importHfReworkDetail',
        printUrl: '/jmreport/view/1076733788150370304',
        editBatch: '/production/hfRework/editBatchHfReworkDetail'
      },
      dictOptions: {}
    }
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importUrl}/${this.mainId}`
    },
    printUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.printUrl}`
    }
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    printAll() {
      const printWindow = window.open(`${this.printUrl}?id=${this.mainId}&token=${store.getters.token}`)
      // 监听新窗口加载完成
      printWindow.onload = function() {
        printWindow.document.title = '自定义打印标题' // 修改标题
      }
    },
    loadData(arg) {
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSourceDefault = JSON.parse(JSON.stringify(this.dataSource))
            this.materialCodes = this.dataSource.map(item => item.materialCode)
            this.ipagination.total = res.result.total
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDelete(code) {
      let that = this
      Modal.confirm({
        title: '确认删除?',
        content: '如果数据已被关联，则不能删除',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          deleteAction(that.url.delete, { materialCode: code, sourceId: this.mainId }).then(res => {
            if (res.success) {
              //重新计算分页问题
              that.reCalculatePage(1)
              that.$message.success(res.message)
              that.loadData()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          })
          if (that.$refs.detailList) {
            that.$refs.detailList.dataSource = []
          }
        }
      })
    },
    save(record) {
      if (!record.actualInputNumber) {
        this.$message.error('请输入数量')
        return
      }
      let param = Object.assign({}, record)
      param['sourceId'] = this.mainId
      param['sourceSerial'] = this.sourceSerial
      this.loading = false
      if (param.add) {
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      } else {
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      }
    },
    changWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.warehouse_dictText = dictOptions.find(item => item.value === record.warehouse).text
          target.warehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    onMaterialChange([value, data], record) {
      if (this.dataSource.some(item => item.materialCode === data[this.uniqueField])) {
        this.$message.error('物料代码已存在')
        record.materialCode = ''
        return
      }
      // 初始化数据
      objectMerge(record, data, ['id', 'createBy', 'createTime', 'updateBy', 'updateTime'])
    },
    handleEditBatch() {
      if (this.dataSource.length === 0) {
        this.$message.warning('请先添加至少一条明细')
        return
      }
      this.editable = true
    },
    handleAdd() {
      this.dataSource.unshift({ add: true })
      this.editable = true
    },
    handleSaveBatch() {
      // 校验
      // 1. 如果有空数据，直接清除
      this.dataSource = this.dataSource.filter(item => item[this.uniqueField])

      const { added, deleted, modified, hasChanges } = this.diffArraysWithReduce(
        this.dataSourceDefault,
        this.dataSource,
        this.compareFields,
        this.uniqueField
      )
      let body = {
        added: added,
        deleted: deleted,
        modified: modified
      }
      if (hasChanges) {
        postAction(this.url.editBatch, body, { params: { sourceId: this.mainId } }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.error(res.message)
          }
        })
      }
      this.editable = false
    },
    handleCancel() {
      const { hasChanges } = this.diffArraysWithReduce(
        this.dataSourceDefault,
        this.dataSource,
        this.compareFields,
        this.uniqueField
      )
      if (hasChanges) {
        Modal.confirm({
          title: '确认取消编辑?',
          content: `数据未保存，确认取消编辑？`,
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            this.loadData()
            this.editable = false
          },
          onCancel: () => {}
        })
      } else {
        this.editable = false
      }
    },
    openQuickInputModal() {
      this.$refs.quickInputModal.visible = true
      let uniqueData = this.dataSource.reduce((acc, cur) => {
        if (acc.find(item => item.materialCode === cur.materialCode)) {
          return acc
        }
        acc.push(cur)
        return acc
      }, [])
      for (const cur of uniqueData) {
        const targetList = this.dataSource.filter(item2 => item2.materialCode === cur.materialCode)
        for (const target of targetList) {
          if (target['warehouse_dictText'] === '车间良品仓') {
            cur['goodId'] = target.id
          }
          if (target['warehouse_dictText'] === '车间不良品仓') {
            cur['defectiveId'] = target.id
          }
          if (target['warehouse_dictText'] === '车间报废仓') {
            cur['scrapId'] = target.id
          }
        }
      }
      this.$refs.quickInputModal.dataSource = uniqueData
    },
    handleDeleteVirtual() {
      this.dataSource = this.dataSource.filter(item => this.selectedRowKeys.indexOf(item[this.uniqueField]) === -1)
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
/* 穿透 Ant Design 的表单项控制样式 */
.cust-erp-sub-tab ::v-deep .ant-form-item-control {
  position: relative;
  line-height: 0;
  zoom: 1;
}
</style>
